from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.generics import CreateAPIView, RetrieveAPIView, UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from rest_framework import status
from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
from rest_framework.decorators import action
from django_redis import get_redis_connection
from rest_framework_jwt.views import ObtainJSONWebToken

from .models import User, Address
from . import serializers
from . import constants
from goods.models import SKU
from carts.utils import merge_cart_cookie_to_redis
# Create your views here.
class UserView(CreateAPIView):
    """用户注册"""

    # 指定序列器，剩下的CreateAPIView都做完了
    serializer_class = serializers.CreateUserSerialzier

class MobileCountView(APIView):
    """判断手机好是否重复"""
    def get(self,request,mobile):
        count = User.objects.filter(mobile=mobile).count()

        # 构造响应数据
        data = {
            'mobile':mobile,
            'count':count
        }

        # 响应数据
        return Response(data)

class UsernameCountView(APIView):
    """判断用户名是否存在"""
    def get(self, request, username):
        # 使用username作为条件查询满足条件的记录的数量
        count = User.objects.filter(username=username).count()

        # 构造响应数据
        data = {
            'username': username,
            'count': count
        }

        # 响应数据
        return Response(data)

class UserDetailView(RetrieveAPIView):
    """用户基本信息"""

    # 指定序列化器
    serializer_class = serializers.UserDetailSerializer
    # 指定权限：只有登录用户才能访问该接口
    permission_classes = [IsAuthenticated]

    def get_object(self):
        """重写该方法，告诉序列化器要序列化的登录用户数据
        user是经过JSONWebTokenAuthentication认证之后的user
        经过permission_classes的权限之后，能够进入这里一定是登录用户
        """
        return self.request.user

class EmailView(UpdateAPIView):
    """添加邮箱"""

    # 指定序列化器
    serializer_class = serializers.EmailSerializer
    # 指定权限：只有登录用户才能访问该接口
    permission_classes = [IsAuthenticated]

    def get_object(self):
        """重写该方法，告诉序列化器要序列化的登录用户数据
        user是经过JSONWebTokenAuthentication认证之后的user
        经过permission_classes的权限之后，能够进入这里一定是登录用户
        """
        return self.request.user

# url(r'^emails/verification/$', views.VerifyEmailView.as_view()),
class VerifyEmailView(APIView):
    """实现邮箱的验证激活"""
    def get(self,request):
        # 从查询字符串中读取token
        token = request.query_params.get('token')
        if not token:
            return Response({'message':'缺少token'},status=status.HTTP_400_BAD_REQUEST)

        # 在从token中读取用户信息，直接读取token中的user
        user = User.check_email_verify_token(token)
        if not user:
            return Response({'message':'无效token'},status=status.HTTP_400_BAD_REQUEST)

        # 最后修改用户的email_active字段为True
        user.email_active = True
        user.save()

        # 响应结果
        return Response({'message':'OK'})


class AddressViewSet(mixins.CreateModelMixin,GenericViewSet):
    """用户地址管理视图集，增删改差"""

    # 指定序列化器
    serializer_class = serializers.UserAddressSerializer
    # 指定用户登陆才能进行增删改查
    permission_classes = [IsAuthenticated]

    # POST /address/
    def create(self,request,*args,**kwargs):
        """重写视图集的create行为，用于新增地址"""

        # 判断用户的地址总数是否大于上线
        # count = Address.objects.filter(user=request.user).count()
        count = request.user.addresses.count()
        if countk > constants.USER_ADDRESS_COUNTS_LIMIT:
            return Response({'message':'超出地址上线'},status=status.HTTP_400_BAD_REQUEST)

        # 补充父类之后的写法
        return super().create(request, *args, **kwargs)
        # # 获取序列化器对象
        # serializer = self.get_serializer(data=request.data)
        # # 校验
        # serializer.is_valid(raise_exception=True)
        # # 执行保存
        # serializer.save()
        # # 响应序列化之后的数据
        # return Response(serializer.data, status=status.HTTP_201_CREATED)

    def get_queryset(self):
        return self.request.user.addresses.filter(is_deleted=False)

    # GET /addresses/
    def list(self, request, *args, **kwargs):
        """
        用户地址列表数据
        """
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        user = self.request.user
        return Response({
            'user_id': user.id,
            'default_address_id': user.default_address_id,
            'limit': constants.USER_ADDRESS_COUNTS_LIMIT,
            'addresses': serializer.data,
        })

    # delete /addresses/<pk>/
    def destroy(self, request, *args, **kwargs):
        """
        处理删除
        """
        address = self.get_object()

        # 进行逻辑删除
        address.is_deleted = True
        address.save()

        return Response(status=status.HTTP_204_NO_CONTENT)

    # put /addresses/pk/status/
    @action(methods=['put'], detail=True)
    def status(self, request, pk=None):
        """
        设置默认地址
        """
        address = self.get_object()
        request.user.default_address = address
        request.user.save()
        return Response({'message': 'OK'}, status=status.HTTP_200_OK)

    # put /addresses/pk/title/
    # 需要请求体参数 title
    @action(methods=['put'], detail=True)
    def title(self, request, pk=None):
        """
        修改标题
        """
        address = self.get_object()
        serializer = serializers.AddressTitleSerializer(instance=address, data=request.data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Response(serializer.data)


# url(r'^browse_histories/$', views.UserBrowsingHistoryView.as_view()),
class UserBrowsingHistoryView(CreateAPIView):
    """保存用户的浏览记录"""

    # 指定序列化器
    serializer_class = serializers.UserBrowsingHistorySerializer
    # 只有登陆用户才能保存浏览记录
    permission_classes = [IsAuthenticated]


    # 因为CreateAPIView继承自view所以可以在定义一个get
    def get(self,request):
        """获取用户浏览记录"""
        # 获取链接到reidis的对象
        redis_conn = get_redis_connection('history')
        # 查询处redis中的浏览记录 sku_ids == ['1','2',...]

        # 查询出redis中的浏览记录 sku_ids == ['1', '2', ......]
        sku_ids = redis_conn.lrange('history_%s' % request.user.id, 0, -1)

        使用sku_ids查询出sku
        sku_list = []
        for sku_id in sku_ids:
            sku = SKU.objects.get(id=sku_id)
            sku_list.append(sku)

        # 序列化sku_list
        serializers = serializers.SKUSerializer(sku_list,many=True)

        return Response


class UserAuthorizeView(ObtainJSONWebToken):
    """
    重写JWT登陆的视图c
    追加合并购物车的业务逻辑,重写post
    """
    def post(self,request,*args,**kwargs):
        # 记得保证JWT登陆的业务逻辑不变
        response = super().post(request, *args, **kwargs)

        # 读取认证后的user
        serializer = self.get_serializer(data = request.data)
        if serializer.is_valid():
            user = serializer.object.get('user') or request.user

            # 追加合并购物车业务逻辑
            response = merge_cart_cookie_to_redis(request=request, user=user, response=response)

        return response

    """
    这个是源代码,我们在上面重写了这个方法
     def post(self, request, *args, **kwargs):
         serializer = self.get_serializer(data=request.data)

         if serializer.is_valid():
             user = serializer.object.get('user') or request.user
             token = serializer.object.get('token')
             response_data = jwt_response_payload_handler(token, user, request)
             response = Response(response_data)
             if api_settings.JWT_AUTH_COOKIE:
                 expiration = (datetime.utcnow() +
                               api_settings.JWT_EXPIRATION_DELTA)
                 response.set_cookie(api_settings.JWT_AUTH_COOKIE,
                                     token,
                                     expires=expiration,
                                     httponly=True)
             return response

         return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
     """